package com.example.opentiktok;

import android.content.Intent;
import android.graphics.Bitmap;
import android.net.http.SslError;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.JavascriptInterface;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import org.json.JSONException;
import org.json.JSONObject;

import java.net.URLDecoder;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


/**
 * facebook 浏览页面
 */
public class BrowseFragment extends Fragment {
    //webView us标识 PC
    public static String KEY_WEBVIEW_USERAGENTSTRING_PC ="Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.134 Safari/537.36";
    WebView webview;
    private String url = "";
    String title;           //标题
    String from = "";
    protected static final FrameLayout.LayoutParams COVER_SCREEN_PARAMS = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
    FrameLayout fullscreenContainer;
    WebChromeClient.CustomViewCallback customViewCallback;
    View customView;
    //是否是启动加载页面
    boolean fastLoadPage = false;



    public static BrowseFragment newInstance() {
        BrowseFragment fragment = new BrowseFragment();
        return fragment;
    }


    private void load() {
        if (url != null && (url.startsWith("http") || url.startsWith("www."))) {
            try {
                webview.loadUrl(URLDecoder.decode(url, "UTF-8"));
            } catch (Exception e) {
                webview.loadUrl(url);
                e.printStackTrace();
            }
        }
    }

    @Override
    public void onDestroy() {
        if (webview != null) {
            try {
                webview.stopLoading();
                webview.destroy();
                webview = null;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        super.onDestroy();
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return initView(inflater, container, savedInstanceState);
    }

    public View initView( LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {


        View inflate = inflater.inflate(R.layout.fragment_browse, container, false);
        webview = inflate.findViewById(R.id.webview);
        initData(savedInstanceState);
        return  inflate;

    }


    public void initData( Bundle savedInstanceState) {
        url = "https://www.tiktok.com/@simplydiedinside/";
//        url = "https://www.tiktok.com/login/";
        webview.getSettings().setSupportZoom(true);

//        webview.getSettings().setBuiltInZoomControls(true);
        webview.setWebContentsDebuggingEnabled(true);
        webview.getSettings().setJavaScriptEnabled(true);// 支持javascript
        webview.addJavascriptInterface(new JavaObjectJsInterface(), "java_obj");
//        webview.addJavascriptInterface(new BrowseFragment().Native(), "native");
        //webView ssl错误忽略
        webview.setWebViewClient(new WebViewClient() {
            @Override
            public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {

            }

            // 依然在webview打开新页面
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                return true;
            }

            @Override
            public boolean shouldOverrideKeyEvent(WebView view, KeyEvent event) {
                return super.shouldOverrideKeyEvent(view, event);
            }

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                // 通过内部类定义的方法获取html页面加载的内容，这个需要添加在webview加载完成后的回调中
                view.loadUrl("javascript:window.java_obj.onHtml(document.body.innerHTML);");
                /**
                 * js注入
                 */
                injectJsSample2();
                super.onPageFinished(view, url);


            }

            @Override
            public void onScaleChanged(WebView view, float oldScale,
                                       float newScale) {
                // TODO Auto-generated method stub
                super.onScaleChanged(view, oldScale, newScale);
                webview.requestFocus();
                webview.requestFocusFromTouch();
            }
        });


        WebSettings settings = webview.getSettings();



        setUserAgentStringPc();

        String setUserAgentString = settings.getUserAgentString();

        Log.d("userAgentString ", "setUserAgentString " + setUserAgentString);
        load();
        fastLoadPage = true;
    }

    /**
     * 设置PC 标识
     */
    private void setUserAgentStringPc() {
        setUserAgentString(KEY_WEBVIEW_USERAGENTSTRING_PC);
    }

    /**
     * 设置Android 标识
     */
//    private void setUserAgentStringAndroid() {
//        String webViewUs = SPUtils.getInstance().get(Constants.SP_WEBVIEW_USERAGENTSTRING_ANDROID, "");
//        if (ValueUtils.isStrNotEmpty(webViewUs)) {
//            setUserAgentString(webViewUs);
//        }
//
//    }

    /**
     * 设置PC标识
     *
     * @param us 标识
     */
    private void setUserAgentString(String us) {
        if (null!=webview) {
            webview.getSettings().setUserAgentString(us);
        }
    }


    private void injectJsSample2() {
        String tmp1 = "javascript: function f1() {  var loginButton = document.getElementsByClassName('login-button').length; window.java_obj.loginButton(loginButton);   }";
        String tmp2 = "javascript: function f2() {  var links = document.getElementsByClassName('jsx-176839946 video-feed compact')[0];var testTarget = links.getElementsByClassName(\"jsx-2261688415 video-feed-item three-column-item\")[0];var _ratio_ = links.getElementsByClassName(\"jsx-176839946 video-feed-item-wrapper\")[0];  window.java_obj.jsMethod(_ratio_.getAttribute(\"href\"));   }";
        String tmp3= "javascript: function f3() { var tiktok_player_icon= document.getElementsByClassName('tiktok-player-icon').length;  window.java_obj.thumbsUp(tiktok_player_icon);   }";
        String tmp4= "javascript: function f4() { document.getElementsByClassName('tiktok-player-icon')[0].click(); setTimeout(function(){document.getElementsByClassName('tiktok-player-icon')[0].click()},50); }";
        // 先注入1
        webview.loadUrl(tmp1);
        webview.loadUrl(tmp2);
        webview.loadUrl(tmp3);
        webview.loadUrl(tmp4);
        webview.loadUrl("javascript: f1();");
        webview.loadUrl("javascript: f2();");
        webview.loadUrl("javascript: f3();");
    }

    /**
     * 双击点赞
     */
    public  void  tiktokPlayerIcon(){
        //双击点赞
        webview.loadUrl("javascript: f4();");




    }




    /**
     * 逻辑处理
     *
     * @author linzewu
     */
    public class JavaObjectJsInterface {
        @JavascriptInterface // 要加这个注解，不然调用不到
        public void jsLogs(String jsLogs) {
            //Log.i("CDH", paramFromJS);
            System.out.println("js返回结果 jsLogs " + jsLogs);//处理返回的结果

        }
        @JavascriptInterface // 要加这个注解，不然调用不到
        public void thumbsUp(int thumbsUpNum) {
            //Log.i("CDH", paramFromJS);
            System.out.println("js返回结果 thumbsUpNum " + thumbsUpNum);//处理返回的结果
//
            if (thumbsUpNum > 0) {
               //点赞
                tiktokPlayerIcon();
            }
        }
    @JavascriptInterface // 要加这个注解，不然调用不到
        public void loginButton(int loginButtonNum) {
            //Log.i("CDH", paramFromJS);
            System.out.println("js返回结果 loginButton " + loginButtonNum);//处理返回的结果

            if (loginButtonNum > 0) {
                //未登录
                if (fastLoadPage) {
                    //不是第一次加载，提示去登录
                fastLoadPage = false;
                }
            } else {

                    //已经登录



            }
        }

        @JavascriptInterface // 要加这个注解，不然调用不到
        public void jsMethod(String paramFromJS) {
            //Log.i("CDH", paramFromJS);
            System.out.println("js返回结果" + paramFromJS);//处理返回的结果
        }

        @JavascriptInterface // 要加这个注解，不然调用不到
        public void onHtml(String html) {
            LogUtil.d("html_info  " + html);

        }

    }

    /**
     * 截取内容
     *
     * @param urlStr
     */
    private String getVideoUrl(String urlStr, String key) {
        String str = "";
        JSONObject jsonObject = null;
        try {
            jsonObject = new JSONObject("{" + urlStr + "}");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        if (null != jsonObject) {
            str = jsonObject.optString(key);
        }
        LogUtil.d("urlStr==" + str);

        return str;

    }

    /**
     * 从json字符串中取一个Key的值
     *
     * @param html
     * @param key        video_url:视频地址，封面：display_url
     * @param patternSrt
     * @return
     */
    public String getJsonTag(String html, String key, String patternSrt) {
        String videoUrl = null;


        Pattern r = Pattern.compile(patternSrt);
        Matcher m = r.matcher(html);
        while (m.find()) {
            LogUtil.d("video_url" + m.group(0));
            videoUrl = m.group(0);
            break;
        }

        return videoUrl;
    }

    public void get() {
        // 调用JavaAndJavaScriptCall.html中javaCallJs(arg)函数
        if (null != webview) {
            webview.loadUrl("javascript:javaCallJs(" + "'" + "java调js成功" + "'" + ")");

        }
    }


    private class JsToJava {
        public void jsMethod(String paramFromJS) {
            //Log.i("CDH", paramFromJS);
            System.out.println("js返回结果" + paramFromJS);//处理返回的结果
        }
    }
}